package com.submit.demo.controller;

import com.submit.demo.annotation.AuthIgnore;
import com.submit.demo.common.api.CommonPage;
import com.submit.demo.common.api.CommonResult;
import com.submit.demo.model.Collector;
import com.submit.demo.model.Submitter;
import com.submit.demo.service.ColSubService;
import com.submit.demo.service.CollectorService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("col")
public class CollectorController {
    @Autowired
    private CollectorService collectorService;

    @Autowired
    private ColSubService colSubService;

    @AuthIgnore
    @ApiOperation("获取该收集人管理的所有提交人")
    @ResponseBody
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public CommonResult<List<Submitter>> listAll(String cid){
        return CommonResult.success(colSubService.listAll(cid));
    }

    @AuthIgnore
    @ApiOperation("获取所有收集人")
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<Collector>> getList(@RequestParam(defaultValue = "25") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum){
        return CommonResult.success(collectorService.fetchAll(pageNum, pageSize));
    }

    @AuthIgnore
    @ApiOperation("新建提交人")
    @ResponseBody
    @RequestMapping(value = "/crCol", method = RequestMethod.GET)
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public CommonResult crCol(@RequestParam("name") String name, @RequestParam("phone") String phone){
        Collector collector = new Collector();
        collector.setName(name);
        collector.setPhone(phone);
        collector.setStatus(1);
        Integer result = collectorService.createCollector(collector);
        if(result == -1) return CommonResult.failed("添加失败");
        else return CommonResult.success(null,"添加成功");
    }

    @AuthIgnore
    @ApiOperation("批量导入收集人")
    @ResponseBody
    @RequestMapping(value = "/impCol", method = RequestMethod.POST)
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public CommonResult impCol(MultipartFile file){
        int result = collectorService.insertFromCsv(file);
        if(result > 0) return CommonResult.success(null, "创建成功");
        return CommonResult.failed("创建失败");
    }

    @AuthIgnore
    @ApiOperation("删除提交人")
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.GET)
    //@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    public CommonResult del(String cid){
        Integer result = collectorService.deleteCollector(cid);
        if(result > 0) return CommonResult.success(null, "删除成功");
        return CommonResult.failed("删除失败");
    }


}
